//
//  String + Regular.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/7.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import Foundation

extension String {

    func sinaSource() ->String {
        
        /*
        pattern: 匹配规则
        1. . : 匹配任何字符串,不包括换行
        2. * : 匹配任意多数量的字符
        3. ? : 尽可能少的匹配
        4. (): 捕获()里面的内容也作为匹配结果返回
        */
        let pattern = ">(.*?)<"
        
        // options: DotMatchesLineSeparators .可以匹配换行
        let regualr = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        
        // string: 从哪个内容里面来查找
        // NSRange: 要查找的字符串的范围
        /* 返回结果: NSTextCheckingResult
        public var numberOfRanges: Int { get } : 匹配到的范围数量
        public func rangeAtIndex(idx: Int) -> NSRange : 根据idx获取匹配范围
        */
        let result = regualr.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0,length: self.characters.count))
        
        let count = result?.numberOfRanges ?? 0
        
        if count > 1{
        
            let range = result?.rangeAtIndex(1)
            
            let subString = (self as NSString).substringWithRange(range!)
            
            return subString
        
        }else {
            return "沒匹配到來源"
        }
        
    }

}